#!usr/bin/node

const mysql = require('mysql2/promise'),
      {con,ResData} = require('./common.js');

async function getImagesCount() {
  const res = new ResData();

  const sql = `select count(id) as count from images;`;

  let [rows] = await con.execute(sql);
  res.count = rows[0].count;

  return res;
}

async function getImagesByPage(page,limit) {
  const res = new ResData();

  const sql = `select * from images order by id limit ${(page-1)*limit},${limit};`,
  sqlCount = `select count(id) as count from images;`;

  let [rows] = await con.execute(sql);
  res.data = rows;

  //rows = await con.execute(sqlCount);
  
  //res.count = rows[0][0].count;

  return res;
};

async function insertImages(imgPath,name,time) {
  const sql = `insert into images(image_path,image_name,create_time) values("${imgPath}","${name}","${time}");`;

  await con.execute(sql);
}

async function deleteFileByID(id) {
  const selsql = `select image_name from images where id = "${id}";`,
  sql = `delete from images where id = "${id}";`;

  let res = '';

  res = await con.execute(selsql);

  await con.execute(sql);

  return res;
}

module.exports = {
  getImagesCount,
  getImagesByPage,
  insertImages,
  deleteFileByID
};
